<?php

class PDFUtility {
		
		protected static $eMethod = "AES-256-CBC";
		protected static $sHash = "25c6c7ff35b9979b151f2136cd13b0ff";
		protected static $iv = 1234567890343343;
		
		public static function getTemporaryDirectory() {
			return "/home/aranyak/public_html/pdf/";
			return sys_get_temp_dir();
		}
		
		public static function getAppBaseURL() {
			
			$scriptLocation = $_SERVER["PHP_SELF"];
			$parts = explode("/",$scriptLocation);
			if(is_array($parts)) {
				unset($parts[count($parts)-1]);
				$baseLocation = implode("/",$parts)."/";
			}
			return "http://".$_SERVER['SERVER_NAME'].$baseLocation;
		}
		
		public static function makeUniqueHashFromParams($params) {
			return openssl_encrypt(json_encode($params), PDFUtility::$eMethod, PDFUtility::$sHash,0,PDFUtility::$iv);
		}
		
		public static function makeParamsFromUniqueHash($hash) {
			
			//Hack : replace space with + 
			$hash = str_replace(" ","+",$hash);
			return  (Array)json_decode(openssl_decrypt($hash, PDFUtility::$eMethod, PDFUtility::$sHash,0,PDFUtility::$iv));
		}
		
		public static function getPDFDownloadURL($action,$params) {
			$params["action"] = $action;
			$hash = PDFUtility::makeUniqueHashFromParams($params);
			return PDFUtility::getAppBaseURL()."pdf.php?download&hash=".urlencode($hash);
		}
		
		public static function generatePDFFromHtml($url) {
			$file = md5(rand().rand().md5(rand())).".pdf";
			$outPutFile = PDFUtility::getTemporaryDirectory().$file;
			//$command = "/home/aranyak/public_html/wkhtmltopdf --header-center \" En-View Motor Tool - Reports \" --footer-center \"Page [page] of [toPage]\" \"{$url}\" \"{$outPutFile}\"";
			$command = "/home/aranyak/public_html/wkhtmltopdf \"{$url}\" \"{$outPutFile}\"";
			$output = shell_exec($command);
			if(file_exists($outPutFile)) {
				header('Content-Type: application/octet-stream');
				header('Content-Disposition: attachment; filename="'.$file);
				echo file_get_contents($outPutFile);
				//echo "<script> window.location = \"http://dev.en-view.com/~aranyak/pdf/{$file}\";</script>";
			}
		}
		
		//;
	}
?>